package com.xszx.servlet.user.login;

import com.xszx.bean.User;
import com.xszx.dao.UserDao;
import com.xszx.dao.impl.UserDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {
    static UserDao userDao = new UserDaoImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        if (username == null && password == null) {
            //游客登录
            req.getSession().setAttribute("username", "tourist");
            resp.sendRedirect("GetAllGoodsLimitServlet");
            return;
        }
        User user = userDao.login(username, password);
        if (user == null) {
            //登录失败
            req.setAttribute("msg", "用户名或密码错误");
            resp.sendRedirect("user/log-in.jsp");
        } else {
            req.getSession().setAttribute("username", username);
            req.setAttribute("user", user);
            resp.sendRedirect("GetAllGoodsLimitServlet");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
